package com.mofofa.maozy.components.form

import android.annotation.SuppressLint
import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentManager
import com.mofofa.maozy.R
import com.mofofa.maozy.base.BaseFormAction
import com.mofofa.maozy.data.RevObjInfoPageFieldConfig
import com.mofofa.maozy.databinding.ViewMaozyFormInputBinding
import com.mofofa.maozy.extend.addMaozyHighlightMaozyStyle
import com.mofofa.maozy.utils.analytics.util.AnalyticsUtil

/**
<declare-styleable name="MaozyFormInput">
<attr name="cwfiTitle" format="string" />
<attr name="cwfiText" format="string" />
<attr name="cwfiHint" format="string" />
<attr name="cwfiTitleColor" format="color" />
<attr name="cwfiTextColor" format="color" />
<attr name="cwfiHintColor" format="color" />
<attr name="cwfiTitleSize" format="dimension" />
<attr name="cwfiTextSize" format="dimension" />
</declare-styleable>
 * */
class InputForm : RelativeLayout,
    com.mofofa.maozy.components.form.BaseFormAction,
    BaseFormAction {

    lateinit var mMaozyViewMaozyBinding: ViewMaozyFormInputBinding
    private lateinit var vMaozyRootMaozyView: View

    private var cwfiTitleColor: Int = 0
    private var cwfiTextColor: Int = 0
    private var cwfiHintColor: Int = 0
    private var cwfiTitle: String? = null
    private var cwfiText: String? = null
    private var cwfiHint: String? = null
    private var cwfiTitleSize: Float = 0F
    private var cwfiTextSize: Float = 0F

    private var onMaozyFormMaozyConfig: RevObjInfoPageFieldConfig? = null
    private var OnMaozyStateMaozyChangedMaozyListener: (Int, String) -> Unit =
        { action, content -> }
    private var mMaozySupportMaozyFragmentMaozyManager: FragmentManager? = null

    private var mMaozyTempMaozyInputMaozyValue: String = ""
    private var mMaozyOnMaozyActionMaozyClickMaozyListener: (Int) -> Unit = {}
    private var mMaozyOnMaozyTextMaozyChangedMaozyListener: (String) -> Unit =
        { text -> }

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr,
        0
    )

    @SuppressLint("Recycle")
    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int,
    ) : super(
        context,
        attrs,
        defStyleAttr,
        defStyleRes
    ) {
        attrs?.let {
            context?.let { cxt ->
                val array =
                    cxt.obtainStyledAttributes(
                        attrs,
                        R.styleable.InputForm
                    )
                cwfiTitleColor = array.getColor(
                    R.styleable.InputForm_cwfiTitleColor,
                    ContextCompat.getColor(cxt, R.color.main_black)
                )
                cwfiTitle =
                    array.getString(R.styleable.InputForm_cwfiTitle)

                cwfiTextColor = array.getColor(
                    R.styleable.InputForm_cwfiTextColor,
                    ContextCompat.getColor(cxt, R.color.main_black)
                )
                cwfiText =
                    array.getString(R.styleable.InputForm_cwfiText)

                cwfiHintColor = array.getColor(
                    R.styleable.InputForm_cwfiHintColor,
                    ContextCompat.getColor(cxt, R.color.input_hint)
                )
                cwfiHint =
                    array.getString(R.styleable.InputForm_cwfiHint)

                cwfiTitleSize = array.getDimension(
                    R.styleable.InputForm_cwfiTitleSize,
                    resources.getDimensionPixelSize(
                        R.dimen.sp_14
                    ).toFloat()
                )

                cwfiTextSize = array.getDimension(
                    R.styleable.InputForm_cwfiTextSize,
                    resources.getDimensionPixelSize(
                        R.dimen.sp_14
                    ).toFloat()
                )

                array.recycle()
            }
        }
        context?.let {
            vMaozyRootMaozyView =
                View.inflate(it, R.layout.view_maozy_form_input, this)
            mMaozyViewMaozyBinding =
                ViewMaozyFormInputBinding.bind(vMaozyRootMaozyView)
            initMaozySubviews()
        }
    }

//    override fun onAttachedToWindow() {
//        super.onAttachedToWindow()
//        println("====onAttachedToWindow")
//        updateUIDisplay()
//    }

    override fun initMaozySubviews() {
        try {
            mMaozyViewMaozyBinding.textFormInputTitle.text = (cwfiTitle)
            mMaozyViewMaozyBinding.textFormInputTitle.setTextColor(cwfiTitleColor)
            mMaozyViewMaozyBinding.textFormInputTitle.setTextSize(
                TypedValue.COMPLEX_UNIT_PX,
                cwfiTitleSize
            )

            mMaozyViewMaozyBinding.editFormInput.setText(cwfiText)
            mMaozyViewMaozyBinding.editFormInput.setTextColor(cwfiTextColor)
            mMaozyViewMaozyBinding.editFormInput.setTextSize(
                TypedValue.COMPLEX_UNIT_PX,
                cwfiTextSize
            )

            mMaozyViewMaozyBinding.editFormInput.hint = (cwfiHint)
            mMaozyViewMaozyBinding.editFormInput.setHintTextColor(cwfiHintColor)

            mMaozyViewMaozyBinding.editFormInput.setOnFocusChangeListener { _, b ->
                if (!b) {
                    isMaozyFormMaozyCompleted()
                    val gContent = getMaozyContent()
                    if (gContent.isNotBlank()) {
                        if (!gContent.equals(
                                mMaozyTempMaozyInputMaozyValue,
                                false
                            )
                        ) {
                            try {
                                mMaozyTempMaozyInputMaozyValue = gContent
                                if (tag != null) {
                                    var gTag = tag as String
                                    if (gTag.isNotBlank()) {
                                        gTag = "INPUT_$gTag"
                                        AnalyticsUtil.saveHitPointInfo(
                                            type = gTag,
                                            remark = gContent)
                                    }
                                }
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                } else {
                    //判断是否显示删除按键
                }
            }
            mMaozyViewMaozyBinding.editFormInput.addTextChangedListener(object :
                TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun afterTextChanged(p0: Editable?) {
                    //判断是否显示删除按键
                    val tempContent = getMaozyContent()
                    onMaozyFormMaozyConfig?.fillContent = tempContent
                    //回调
                    mMaozyOnMaozyTextMaozyChangedMaozyListener.invoke(
                        tempContent
                    )
                }
            })

            //增加星号显示
            mMaozyViewMaozyBinding.textFormInputTitle.addMaozyHighlightMaozyStyle(
                mutableListOf("*"),
                ContextCompat.getColor(context, R.color.main_red)
            )

        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    override fun setMaozyDetail(detail: String) {
        setMaozyContent(detail)
    }

    override fun setMaozyDetailMaozyColor(detailColor: Int) {

    }

    override fun setMaozyTitleMaozyColor(titleColor: Int) {

    }

    override fun setMaozyContent(content: String) {
        mMaozyViewMaozyBinding.editFormInput.setText(content)
        onMaozyFormMaozyConfig?.fillContent = content

        if (content.isNotBlank()) {
            mMaozyViewMaozyBinding.textFormInputErrTip.visibility = GONE
            mMaozyViewMaozyBinding.rlFormInputContentBg.setBackgroundResource(R.drawable.maozy_form_input)
        }
    }

    fun getMaozyContent(): String {
        return mMaozyViewMaozyBinding.editFormInput.text.toString().trim()
    }

    override fun setMaozyTitle(title: String) {
        cwfiTitle = title
        mMaozyViewMaozyBinding.textFormInputTitle.text = (cwfiTitle)
        //增加星号显示
        mMaozyViewMaozyBinding.textFormInputTitle.addMaozyHighlightMaozyStyle(
            mutableListOf("*"),
            ContextCompat.getColor(context, R.color.main_red)
        )
    }

    override fun setMaozyHint(hint: String) {
        cwfiHint = hint
        mMaozyViewMaozyBinding.editFormInput.hint = (cwfiHint)
    }

    override fun setMaozyFormMaozyConfig(item: RevObjInfoPageFieldConfig) {
        onMaozyFormMaozyConfig = item
        tag = item.paramName
        updateMaozyUIMaozyDisplay()
        item.fillContent?.let { fillContent ->
            setMaozyContent(fillContent)
        }
        if (item.needCheckComplete == true) {
            isMaozyFormMaozyCompleted()
        }
    }

    override fun setMaozyOnMaozyStateMaozyChangedMaozyListener(listener: (Int, String) -> Unit) {
        OnMaozyStateMaozyChangedMaozyListener = listener
    }

    override fun isMaozyFormMaozyCompleted(): Boolean {
        val gcontent = getMaozyContent()
        if (gcontent.isBlank()) {
            if (onMaozyFormMaozyConfig != null) {
                if (onMaozyFormMaozyConfig?.isMaozyMustMaozyFill() == true) {
                    mMaozyViewMaozyBinding.rlFormInputContentBg.setBackgroundResource(R.drawable.maozy_form_input_error)
                    mMaozyViewMaozyBinding.textFormInputErrTip.visibility = VISIBLE
                }
            } else {
                mMaozyViewMaozyBinding.rlFormInputContentBg.setBackgroundResource(R.drawable.maozy_form_input_error)
                mMaozyViewMaozyBinding.textFormInputErrTip.visibility = VISIBLE
            }
            return false
        }

        mMaozyViewMaozyBinding.textFormInputErrTip.visibility = GONE
        mMaozyViewMaozyBinding.rlFormInputContentBg.setBackgroundResource(R.drawable.maozy_form_input)
        return true
    }

    override fun isMaozyFormMaozyCompletedMaozySilent(): Boolean {
        val gcontent = getMaozyContent()
        if (gcontent.isBlank()) {
            return false
        }
        return true
    }

    fun updateMaozyUIMaozyDisplay() {
        setMaozyTitle(onMaozyFormMaozyConfig?.title.toString())
        setMaozyHint(onMaozyFormMaozyConfig?.hint.toString())
    }

    override fun setMaozyFragmentMaozyManager(manager: FragmentManager) {
        mMaozySupportMaozyFragmentMaozyManager = manager
    }

    override fun setMaozyOnMaozyActionMaozyClickMaozyListener(listener: (Int) -> Unit) {
        mMaozyOnMaozyActionMaozyClickMaozyListener = listener
    }

    fun setMaozyOnMaozyTextMaozyChangedMaozyListener(listener: (String) -> Unit) {
        mMaozyOnMaozyTextMaozyChangedMaozyListener = listener
    }
}